package com.mh.utils;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;

/**
 * Date:2025/3/14
 * author:zmh
 * description: AI工具类
 **/

@Component
public class AiUtils {

    // 阿里百炼API KEY
    @Value("${API_KEY}")
    private String API_KEY;

    // 图片本地路径
    @Value("${FILEPATH}")
    private String localPath;

    /**
     * 图片视觉处理 - 单消息处理
     * @return 识别垃圾的分类结果
     * @param picName 图片名称
     * @param question 用户的问题
     * @throws NoApiKeyException ·
     * @throws UploadFileException ·
     */
    public String visualProcess(String picName, String question) throws NoApiKeyException, UploadFileException, IOException {
        String filePath = "file:///" + localPath + picName;
        MultiModalConversation conv = new MultiModalConversation();

        // 读取prompt喂给AI
        ClassPathResource classPathResource = new ClassPathResource("static/garbageRecognizePrompt.md");
        byte[] bytes = FileCopyUtils.copyToByteArray(classPathResource.getInputStream());
        String promptStr = new String(bytes, StandardCharsets.UTF_8);

        // 构建系统消息
        MultiModalMessage systemMessage = MultiModalMessage.builder().role(Role.SYSTEM.getValue())
                .content(Arrays.asList(Collections.singletonMap("text", promptStr))).build();
        // 构建用户消息
        MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
                .content(Arrays.asList(new HashMap<String, Object>(){{put("image", filePath);}},
                        new HashMap<String, Object>(){{put("text", "这是什么类型的垃圾?");}})).build();
        // 构建请求参数
        MultiModalConversationParam param = MultiModalConversationParam.builder()
                .apiKey(API_KEY)
                .model("qwen-vl-max-latest")
                .messages(Arrays.asList(systemMessage, userMessage))
                .build();
        MultiModalConversationResult result = conv.call(param);

        // 输出结果
        System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));
        return  result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text").toString();
    }

    /**
     * 文本处理
     * @param question 用户的输入内容
     * @return ·
     */
    public String textProcess(String question) throws NoApiKeyException, InputRequiredException {
        Generation gen = new Generation();

        // 读取prompt喂给AI
        ClassPathResource classPathResource = new ClassPathResource("static/garbageRecognizePromptText.md");
        byte[] bytes = new byte[0];
        try {
            bytes = FileCopyUtils.copyToByteArray(classPathResource.getInputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String promptStr = new String(bytes, StandardCharsets.UTF_8);

        // 系统消息
        Message systemMsg = Message.builder()
                .role(Role.SYSTEM.getValue())
                .content(promptStr)
                .build();
        // 用户输入
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content(question)
                .build();
        // 构造请求变量
        GenerationParam param = GenerationParam.builder()
                .apiKey(API_KEY)
                .model("qwen-plus")
                .messages(Arrays.asList(systemMsg, userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .build();
        // 执行对话识别
        GenerationResult result = gen.call(param);
        // 输出
        System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent());
        return result.getOutput().getChoices().get(0).getMessage().getContent();
    }
}
